﻿using System;
using System.ComponentModel;
using System.Configuration;
using System.Globalization;

namespace Nana.Web.Compressing
{
  public sealed class ModuleTypeConverter
    : ConfigurationConverterBase
  {
    internal static readonly string baseNamespace;
    static ModuleTypeConverter()
    {
      baseNamespace = typeof(ModuleTypeConverter).Namespace;
    }

    public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data)
    {
      if (null == data) return null;

      var typeName = data as string;
      if (null == typeName)
        throw new ArgumentOutOfRangeException();

      Type type = Type.GetType(typeName);
      if (null == type)
        type = Type.GetType(baseNamespace + "." + typeName);

      if (null == type)
        type = Type.GetType(baseNamespace + "." + typeName + "FilterFactory", false, true);

      return type;
    }

    public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type)
    {
      if (null == value) return null;

      var typeVal = value as Type;
      if (typeVal == null)
        throw new ArgumentOutOfRangeException();

      return typeVal.AssemblyQualifiedName;
    }
  }

}
